package vip.ola.pay.batchpay.hengshengpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.IPUtility;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.PayInterface;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.batchpay.RSAUtils;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchTrans;
import vip.ola.pay.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.TreeMap;

import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.TRANS_STATUS_SUCCESS;

@RequestMapping("/api/hengshengp")
@Controller
public class HengshengpTransController extends BaseController {

    private static final MyLog _log = MyLog.getLog(HengshengpTransController.class);

    @Autowired
    private RpcCommonService rpcCommonService;

    @Autowired
    public BaseNotify4MchTrans baseNotify4MchTrans;

    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestBody JSONObject object, HttpServletRequest request){
        _log.info("接收HengshengTransController回调：" + object);
        // 判断请求IP是否允许+"："
        String clintIp = IPUtility.getClientIp(request);
        PayInterface payInterface = rpcCommonService.rpcPayInterfaceService.findByCode("hengshengp");
        String whiteIps=payInterface.getRemark();
        _log.info("请求ip为：" + clintIp+"  维护白名单ip： "+ whiteIps);
        if (StringUtils.isEmpty(whiteIps) || !Arrays.asList(whiteIps.split("\\,")).contains(clintIp)){
            _log.info( "IP[" + clintIp + "]不允许访问");
            return "ip fail";
        }
        String transOrderId = object.getString("merchantOrderNo");
        TransOrder payOrder = rpcCommonService.rpcTransOrderService.findByTransOrderId(transOrderId);
        if(payOrder == null){
            return "order not exist!";
        }
        Long orderMoney = BigDecimal.valueOf(object.getLong("amount")).multiply(BigDecimal.valueOf(100)).longValue();
        if (orderMoney.longValue() != payOrder.getAmount().longValue()){
            return "money fail";
        }
        if (payOrder.getStatus() == TRANS_STATUS_SUCCESS || payOrder.getStatus() == TRANS_STATUS_COMPLETE) {
            return "success";
        }
        AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
            return "fail";
        }
        if (!"1".equals(object.getString("status"))){
            _log.info("notify status is error,the mchOrderNo->{},status->{}:",transOrderId,object.getString("status"));
            return "status fail";
        }
        JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
        String publicKey = accountParams.getString("publicKey");
        try {
            Boolean flag = RSAUtils.verify(object, publicKey);
            if (flag){
                String mchId = payPassageAccount.getPassageMchId();
                String queryUrl = accountParams.getString("queryUrl");
                String privateKey = accountParams.getString("privateKey");
                TreeMap<String, String> obj = new TreeMap<String, String>();
                obj.put("version", "1.0.1");
                SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddHHmmss");
                obj.put("submitTime", fm.format(payOrder.getUpdateTime()));
                obj.put("merchantId",mchId);
                obj.put("merchantOrderNo", transOrderId);
                // 生成签名
                StringBuffer paramstr = new StringBuffer();
                for (String pkey : obj.keySet()) {
                    String pvalue = obj.get(pkey);
                    if (pvalue != null && pvalue != "") {
                        paramstr.append(pkey + "=" + pvalue + "&");
                    }
                }
                String paramsrc = paramstr.substring(0, paramstr.length() - 1);
                String queryBytes = RSAUtils.sign(paramsrc, privateKey);
                obj.put("sign", queryBytes);
                _log.info("查询请求={},加密串-》{}",JSONObject.toJSONString(obj),paramsrc);
                String respDetail = HengshengpTransService.call(queryUrl,obj);
                _log.info("HengshengTransController-》订单查询明细返回={}",respDetail);
                if (StringUtils.isNotEmpty(respDetail)){
                    JSONObject resObj = JSON.parseObject(respDetail);
                    if ("0".equals(resObj.getString("code")))
                    {
                        String queryStatus = resObj.getString("status");
                        if (StringUtils.isNotEmpty(queryStatus) && "1".equals(queryStatus) ){
                            String channelOrderNo = object.getString("orderNo");
                            int result =  rpcCommonService.rpcTransOrderService.updateStatus4Success(transOrderId, channelOrderNo);
                            _log.info("更新订单状态为支付成功: result={}", result);
                            if(result == 1){
                                // 通知业务系统
                                baseNotify4MchTrans.doNotify(payOrder, true);
                                return "success";
                            }
                        }else {
                            _log.info("query status is error,the mchOrderNo:"+transOrderId);
                            return "query error";
                        }
                    }else {
                        _log.info("query detail is error,the mchOrderNo:"+transOrderId);
                        return "query detail error";
                    }
                }else {
                    _log.error("订单查询异常，the mchorderno:" +transOrderId);
                    return "query error";
                }
            }else {
                _log.info("sign error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "verfiy fail";
        }
        return "fail!";
    }




}
